package com.vim.modules.web.service;

import com.vim.common.base.Constants;
import com.vim.common.exception.BusinessException;
import com.vim.common.model.exception.BusinessExceptionEnums;
import com.vim.common.utils.IdGen;
import com.vim.common.base.CrudServiceImpl;
import com.vim.common.utils.TokenManager;
import com.vim.modules.web.model.UserInfo;
import com.vim.modules.web.dao.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserInfoService extends CrudServiceImpl<UserInfo> {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Autowired
    public UserInfoService(UserInfoMapper mapper) {
        super(mapper);
    }

    @Override
    public int save(UserInfo entity) {
        entity.setUserId(IdGen.uuid());
        return super.save(entity);
    }

    /**
     * 账户登录
     * @param loginAccount
     * @param loginPassword
     */
    public UserInfo loginByAccount(String loginAccount, String loginPassword) {
        UserInfo userInfo = userInfoMapper.findAccount(loginAccount);
        if(null == userInfo){
            throw new BusinessException(BusinessExceptionEnums.ERROR_USER_LOGIN);
        }
        if(!loginPassword.equals(userInfo.getLoginPassword())){
            throw new BusinessException(BusinessExceptionEnums.ERROR_USER_LOGIN);
        }
        userInfo.setLoginPassword(null);
        userInfo.setToken(TokenManager.applyToken());
        return userInfo;
    }

    /**
     * 手机号登录
     * @param loginPhone
     */
    public UserInfo loginByPhone(String loginPhone) {
        UserInfo userInfo = new UserInfo();
        userInfo.setLoginAccount(loginPhone);
        List<UserInfo> list = findList(userInfo);
        if(null != list && list.size() > 0){
            userInfo = list.get(0);
        }else{
            //注册
            userInfo.setUserName(IdGen.code());
            userInfo.setLoginPassword(Constants.initPassword);
            userInfo.setCreateTime(new Date());
            save(userInfo);
        }
        userInfo.setLoginPassword(null);
        userInfo.setToken(TokenManager.applyToken());
        return userInfo;
    }
}

